//
// DLAddToDesktopHandler.m
//  DLCreateShortcut
//
//  Created by donglei on 16/3/30.
//  Copyright © 2016年 DL. All rights reserved.
//

#import "DLAddToDesktopHandler.h"
#import "HTTPServer.h"
#import "DDLog.h"
#import "DDTTYLogger.h"
#import "DLBase64.h"


#ifdef DEBUG
static const int ddLogLevel = LOG_LEVEL_VERBOSE;
#else
static const int ddLogLevel = LOG_LEVEL_WARN;
#endif

#define DLCSTitle                   @"DLCSTitle"
#define DLCSImageData               @"DLCSImageData"
#define DLCSAPPScheme               @"DLCSAPPScheme"
#define DLCSDataURISchemeContent    @"DLCSDataURISchemeContent"
#define DLAPPDownloadUrl            @"DLAPPDownloadUrl"


@interface DLAddToDesktopHandler()

@property(nonatomic, strong) HTTPServer *myHTTPServer;

///content.html 的沙河路径
@property (nonatomic, copy) NSString *contentDucumentPath;

@end


@implementation DLAddToDesktopHandler

#pragma mark - MainMethod

+(DLAddToDesktopHandler *)sharedInsance {
    
    [DDLog addLogger:[DDTTYLogger sharedInstance]];
    static DLAddToDesktopHandler *_sharedInstance = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        _sharedInstance = [[DLAddToDesktopHandler alloc] init];
    });
    
    return _sharedInstance;
}

/**
 *    @brief    通过Safari添加快捷方式到桌面,如未安装应用会跳转到应用下载地址，如安装应用，会直接打开应用
 *    @param     dataURISchemeImage   data URI scheme
 *    @param     title                快捷方式桌面名称
 *    @param     urlScheme            ios APP的URL Schemes
 *    @param     appDownloadUrl       应用下载地址
 */
- (void)addToDesktopWithDataURISchemeImage:(NSString *)dataURISchemeImage
                                     title:(NSString *)title
                                 urlScheme:(NSString *)urlScheme
                            appDownloadUrl:(NSString *)appDownloadUrl
{
    
    [self addToDesktopWithDataURISchemeImage:dataURISchemeImage
                                       title:title
                                   urlScheme:urlScheme
                              appDownloadUrl:appDownloadUrl
                                   localPort:80];
}




#pragma mark - 把index和content html替换内容写入本地服务器 过度页面通过局域网访问网页
- (void)addToDesktopWithDataURISchemeImage1:(NSString *)dataURISchemeImage
                                      title:(NSString *)title
                                  urlScheme:(NSString *)urlScheme
                             appDownloadUrl:(NSString *)appDownloadUrl
                                  localPort:(int)localPort
{
    
    [self configHttpServerWithPort:localPort];
    NSString *contentHtmlString = [self contentHtmlWithBase64Image:dataURISchemeImage
                                                             title:title
                                                         appScheme:urlScheme
                                                    appDownloadUrl:appDownloadUrl];
    [self configLocalUrlWithHtmlStr:contentHtmlString];
    [self startServer];
    NSString *localAddress = [NSString stringWithFormat:@"http://127.0.0.1:%d",localPort];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:localAddress] options:@{} completionHandler:nil];
    
}

#pragma mark - 把content.html 转成 Base64 替换到index.html 通过局域网访问网页 base64的页面无法加载 复制到浏览器可以正常打开
- (void)addToDesktopWithDataURISchemeImage2:(NSString *)dataURISchemeImage
                                      title:(NSString *)title
                                  urlScheme:(NSString *)urlScheme
                             appDownloadUrl:(NSString *)appDownloadUrl
                                  localPort:(int)localPort
{
    
    [self configHttpServerWithPort:localPort];
    NSString *contentHtmlString = [self contentHtmlWithBase64Image:dataURISchemeImage
                                                             title:title
                                                         appScheme:urlScheme
                                                    appDownloadUrl:appDownloadUrl];
    
    [self configDataUrlWithHtmlStr:contentHtmlString];
    [self startServer];
    NSString *localAddress = [NSString stringWithFormat:@"http://127.0.0.1:%d",localPort];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:localAddress] options:@{} completionHandler:nil];
}

- (void)addToDesktopWithDataURISchemeImage3:(NSString *)dataURISchemeImage
                                      title:(NSString *)title
                                  urlScheme:(NSString *)urlScheme
                             appDownloadUrl:(NSString *)appDownloadUrl
                                  localPort:(int)localPort
{
    [self configHttpServerWithPort:localPort];
    NSString *weixinHtmlPath = [self getWeiXinHTMLTempletPath];
    NSString *weixinHtmlString = [NSString stringWithContentsOfFile:weixinHtmlPath encoding:NSUTF8StringEncoding error:nil];
    [self writeWeiXinHTMLToDocument:weixinHtmlString];
    [self startServer];
    NSString *url = [NSString stringWithFormat:@"http://127.0.0.1:%d/weixin.html?link=%@&title=%@",localPort, urlScheme, title];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{} completionHandler:nil];
    
}

- (void)addToDesktopWithDataURISchemeImage:(NSString *)dataURISchemeImage
                                     title:(NSString *)title
                                 urlScheme:(NSString *)urlScheme
                            appDownloadUrl:(NSString *)appDownloadUrl
                                 localPort:(int)localPort
{
    // 电脑的IP地址
    NSString *ipAddress = @"192.168.8.106";
 
    //  NSString *urlStr = [NSString stringWithFormat:@"http://%@:%d/weixin.html?link=%@&title=%@", ipAddress, localPort, urlScheme, title];
    
     NSString *urlStr = [NSString stringWithFormat:@"http://%@/weixin?link=%@", ipAddress, urlScheme];
    

    //    NSString *urlStringUTF8 = [urlStr stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    
  //    NSString *urlStr = [NSString stringWithFormat:@"http://%@:%d/weixin.html?link=%@", ipAddress, localPort, urlScheme];
    
    NSLog(@"地址：%@", urlStr);
    NSURL *url = [NSURL URLWithString:urlStr];
    [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
    
}


- (void)configDataUrlWithHtmlStr:(NSString *)contentHtmlStr {
    NSString *contentHtmlString = [DLBase64 encodeBase64String:contentHtmlStr];
    //contentHtml 替换到index.html中
    NSString *DataURIString = [NSString stringWithFormat:@"0;data:text/html;charset=utf-8;base64,%@",contentHtmlString];
    //    NSString *DataURIString = [NSString stringWithFormat:@"0;http://127.0.0.1:80?dataurl=%@",contentHtmlString];
    NSString *indexHtmlString = [self indexHtmlWithBase64ContentString:DataURIString];
    [self writeHTMLToDocument:indexHtmlString];
}

- (void)configLocalUrlWithHtmlStr:(NSString *)contentHtmlStr
{
    [self writeContentHTMLToDocument:contentHtmlStr];
    NSString *indexHtmlString = [self configIndexHtml];
    [self writeHTMLToDocument:indexHtmlString];
}
#pragma mark - HttpServerMethod

- (void)configHttpServerWithPort:(int)port
{
    if (!_myHTTPServer) {
        //config HttpServer
        _myHTTPServer = [[HTTPServer alloc] init];
        [_myHTTPServer setType:@"_http._tcp."];
        [_myHTTPServer setPort:port];
        
        //setWebPath
        NSString *serverWebPath = [self getServerWebPath];
        BOOL created = [[NSFileManager defaultManager] createDirectoryAtPath:serverWebPath withIntermediateDirectories:YES attributes:nil error:nil];
        if(created){
            [_myHTTPServer setDocumentRoot:serverWebPath];
        }
        DDLogInfo(@"SettingHttpServerPath:%@", serverWebPath);
    }
    
    DDLogInfo(@"myHTTPServer already started");
}

- (void)startServer
{
    if (_myHTTPServer.isRunning) {
        [_myHTTPServer stop];
    }
    NSError *error;
    if([_myHTTPServer start:&error])
    {
        DDLogInfo(@"Started HTTP Server on port %hu", [_myHTTPServer listeningPort]);
    }
    else
    {
        DDLogError(@"Error starting HTTP Server: %@", error);
    }
}


#pragma mark - HTMLMethod

- (NSString *)contentHtmlWithBase64Image:(NSString *)base64ImageString title:(NSString *)title appScheme:(NSString *)scheme appDownloadUrl:(NSString *)appDownloadUrl
{
    NSString *contentHtmlPath = [self getcontentHTMLTempletPath];
    NSString *contentHtmlString = [NSString stringWithContentsOfFile:contentHtmlPath encoding:NSUTF8StringEncoding error:nil];
    // contentHtml 替换参数
    contentHtmlString = [contentHtmlString stringByReplacingOccurrencesOfString:DLCSImageData withString:base64ImageString];
    contentHtmlString = [contentHtmlString stringByReplacingOccurrencesOfString:DLCSTitle withString:title];
    contentHtmlString = [contentHtmlString stringByReplacingOccurrencesOfString:DLCSAPPScheme withString:scheme];
    contentHtmlString = [contentHtmlString stringByReplacingOccurrencesOfString:DLAPPDownloadUrl withString:appDownloadUrl];
    return contentHtmlString;
    
}

- (NSString *)indexHtmlWithBase64ContentString:(NSString *)contentString {
    NSString *indexHtmlPath = [self getIndexHTMLTempletPath];
    NSString *indexHtmlString = [NSString stringWithContentsOfFile:indexHtmlPath encoding:NSUTF8StringEncoding error:nil];
    indexHtmlString = [indexHtmlString stringByReplacingOccurrencesOfString:DLCSDataURISchemeContent withString:contentString];
    return indexHtmlString;
    
}

#pragma mark - FileMethod

- (void)writeHTMLToDocument:(NSString *)htmlString {
    NSString *serverWebPath = [self getServerWebPath];
    BOOL created = [[NSFileManager defaultManager] createDirectoryAtPath:serverWebPath withIntermediateDirectories:YES attributes:nil error:nil];
    if(created){
        NSData *data = [htmlString dataUsingEncoding:NSUTF8StringEncoding];
        // /var/mobile/Containers/Data/Application/5653C32E-FE56-427D-BCAE-A9EEA96E5582/Documents/DLCreateShortcutWebPath/index.html
        BOOL writeToDucument = [data writeToFile:[NSString stringWithFormat:@"%@/index.html",serverWebPath] atomically:YES];
        if (writeToDucument) {
            DDLogInfo(@"indexHtmlAlreadyWriteToDocument");
        }
    }
    
}

- (void)writeContentHTMLToDocument:(NSString *)htmlString {
    NSString *serverWebPath = [self getServerWebPath];
    BOOL created = [[NSFileManager defaultManager] createDirectoryAtPath:serverWebPath withIntermediateDirectories:YES attributes:nil error:nil];
    if (created) {
        NSData *data = [htmlString dataUsingEncoding:NSUTF8StringEncoding];
        // /var/mobile/Containers/Data/Application/5653C32E-FE56-427D-BCAE-A9EEA96E5582/Documents/DLCreateShortcutWebPath/content.html
        NSString *contentDucumentPath = [NSString stringWithFormat:@"%@/content.html",serverWebPath];
        self.contentDucumentPath = contentDucumentPath;
        BOOL writeToDucument = [data writeToFile:contentDucumentPath atomically:YES];
        if (writeToDucument) {
            DDLogInfo(@"contentHtmlAlreadyWriteToDocument");
        }
    }
}

- (void)writeWeiXinHTMLToDocument:(NSString *)htmlString {
    NSString *serverWebPath = [self getServerWebPath];
    BOOL created = [[NSFileManager defaultManager] createDirectoryAtPath:serverWebPath withIntermediateDirectories:YES attributes:nil error:nil];
    if (created) {
        NSData *data = [htmlString dataUsingEncoding:NSUTF8StringEncoding];
        NSString *contentDucumentPath = [NSString stringWithFormat:@"%@/weixin.html",serverWebPath];
        BOOL writeToDucument = [data writeToFile:contentDucumentPath atomically:YES];
        if (writeToDucument) {
            DDLogInfo(@"index2HtmlAlreadyWriteToDocument");
        }
    }
}

- (NSString *)configIndexHtml {
    NSString *indexHtmlPath = [self getIndexHTMLTempletPath];
    NSString *indexHtmlString = [NSString stringWithContentsOfFile:indexHtmlPath encoding:NSUTF8StringEncoding error:nil];
    //    NSString *urlScheme = [NSString stringWithFormat:@"0;http://127.0.0.1:8080/%@",@"content.html"];
    NSString *urlScheme = [NSString stringWithFormat:@"0;%@",@"http://47.74.52.226:8010/content.html"];
    //    NSString *urlScheme = [NSString stringWithFormat:@"0;file://%@",self.contentDucumentPath];
    indexHtmlString = [indexHtmlString stringByReplacingOccurrencesOfString:DLCSDataURISchemeContent withString:urlScheme];
    return indexHtmlString;
    
}

- (NSString *)getServerWebPath
{
    NSString *serverWebPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"DLCreateShortcutWebPath"];
    NSLog(@"serverWebPath:%@",serverWebPath);
    return serverWebPath;
}

- (NSString *)getIndexHTMLTempletPath
{
    NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"/index.html"];
    NSLog(@"index path:%@",path);
    return path;
}

- (NSString *)getcontentHTMLTempletPath
{
    NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"/content.html"];
    NSLog(@"content path:%@",path);
    return path;
}

- (NSString *)getWeiXinHTMLTempletPath
{
    NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"/weixin.html"];
    NSLog(@"content path:%@",path);
    return path;
}


@end
